package com.example.teesystem.common.utils;

import com.example.teesystem.entityDto.ExamPaperSimpleMessage;
import com.example.teesystem.entityDto.ExaminationIssueList;
import com.example.teesystem.entityDto.IssueBriefMessage;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.jfree.chart.JFreeChart;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;

import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.teesystem.common.utils.ChartUtils.CHART_COLORS;
import static com.example.teesystem.common.utils.ChartUtils.createBarPort;

/**
 * @author pxr
 * @data 2022/4/20 20:05
 */
@AutoConfigurationPackage
public class PdfFontUtil {

    // 基础配置
    private static final String PDF_SITE = "/file/1.pdf";
//    private static final String FONT = "C:/Users/Administrator/Documents/Tencent Files/1332439799/FileRecv/simhei.ttf";
    private static final String FONT = "/file/simhei.ttf";
    private static final String PAGE_TITLE = "PDF数据导出报告";
    // 基础样式
    private static final Font TITLE_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, 20, Font.BOLD);
    private static final Font NODE_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, 15, Font.BOLD);
    private static final Font BLOCK_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, 13, Font.BOLD, BaseColor.BLACK);
    private static final Font INFO_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, 12, Font.NORMAL, BaseColor.BLACK);
    private static final Font CONTENT_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

    private static final String[] TITLE_INDEX = new String[]{"一、", "二、", "三、", "四、"};

    /**
     * 大标题样式获取
     */
    public static Paragraph getParagraph(String content, Font font, Integer alignment) {
        Paragraph paragraph = new Paragraph(content, font);
        if (alignment != null && alignment >= 0) {
            paragraph.setAlignment(alignment);
        }
        return paragraph;
    }

    /**
     * 小标题样式
     */
    public static Paragraph getTitleParagraph(String content, Font font, Integer alignment) {
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setIndentationLeft(20);
        if (alignment != null && alignment >= 0) {
            paragraph.setAlignment(alignment);
        }
        return paragraph;
    }

    /**
     * 选项样式获取
     */
    public static Paragraph getSelectionParagraph(String content, Font font, Integer alignment) {
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setIndentationLeft(50);
        if (alignment != null && alignment >= 0) {
            paragraph.setAlignment(alignment);
        }
        return paragraph;
    }

    /**
     * 图表转图片
     * 图片样式
     */
    public static Image getImage(float width, float height) throws Exception {
        Map<String, Double> map2 = new HashMap<>();
        map2.put("冠心病", (double) 1000);
        map2.put("脑卒中", (double) 700);
        map2.put("肺结核", (double) 600);
        map2.put("糖尿病", (double) 400);
        map2.put("高血压", (double) 100);
        map2.put("精神病", (double) 2000);
        JFreeChart chart = createBarPort("慢病统计结果", map2);
        BufferedImage image1 = chart.createBufferedImage((int) width, (int) height);
        Image image = Image.getInstance(image1, CHART_COLORS[0]);
        image.setAlignment(Image.MIDDLE);
        if (width > 0 && height > 0) {
            image.scaleAbsolute(width, height);
        }
        return image;
    }

    /**
     * 图片插入
     * @param imgPath
     * @param width
     * @param height
     * @return
     * @throws Exception
     */
    public static Image getImage (String imgPath, float width, float height) throws Exception {
        Image image = Image.getInstance(imgPath);
        image.setAlignment(Image.MIDDLE);
        if (width > 0 && height > 0){
            image.scaleAbsolute(width, height);
        }
        return image ;
    }

    /**
     * 表格生成
     */
    public static PdfPTable getPdfPTable01(int numColumns, float totalWidth) throws Exception {
        // 表格处理
        PdfPTable table = new PdfPTable(numColumns);
        // 设置表格宽度比例为%100
        table.setWidthPercentage(100);
        // 设置宽度:宽度平均
        table.setTotalWidth(totalWidth);
        // 锁住宽度
        table.setLockedWidth(true);
        // 设置表格上面空白宽度
        table.setSpacingBefore(10f);
        // 设置表格下面空白宽度
        table.setSpacingAfter(10f);
        // 设置表格默认为无边框
        table.getDefaultCell().setBorder(2);
        table.setPaddingTop(50);
        table.setSplitLate(false);
        return table;
    }

    /**
     * 表格内容
     */
    public static PdfPCell getPdfPCell(Phrase phrase) {
        return new PdfPCell(phrase);
    }

    /**
     * 表格内容带样式
     */
    public static void addTableCell(PdfPTable dataTable, Font font, List<String> cellList) {
        for (String content : cellList) {
            dataTable.addCell(getParagraph(content, font, -1));
        }
    }

    public static void createPdfPage(HttpServletResponse response) {
        try {
            // 创建文档
            Document document = new Document();
            response.setContentType("application/pdf");
            String filename = "exam_report";
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".pdf");
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            // 报告标题
            document.add(PdfFontUtil.getParagraph(PAGE_TITLE, TITLE_FONT, 1));
            document.add(PdfFontUtil.getParagraph("\n商户名称：XXX科技有限公司", INFO_FONT, -1));
            document.add(PdfFontUtil.getParagraph("\n生成时间：2021-09-02\n\n", INFO_FONT, -1));
            // 报告内容
            // 段落标题 + 报表图
            document.add(PdfFontUtil.getParagraph("城市数据分布统计", NODE_FONT, -1));
            document.add(PdfFontUtil.getParagraph("\n· 可视化图表\n\n", BLOCK_FONT, -1));
            // 设置图片宽高
            float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
            float documentHeight = documentWidth / 580 * 320;
            document.add(PdfFontUtil.getImage(documentWidth, documentHeight));
            // 数据表格
            document.add(PdfFontUtil.getParagraph("\n· 数据详情\n\n", BLOCK_FONT, -1));
            PdfPTable dataTable = PdfFontUtil.getPdfPTable01(8, 500);
            // 设置表格
            List<String> tableHeadList = tableHead();
            List<List<String>> tableDataList = getTableData();
            PdfFontUtil.addTableCell(dataTable, CONTENT_FONT, tableHeadList);
            for (List<String> tableData : tableDataList) {
                PdfFontUtil.addTableCell(dataTable, CONTENT_FONT, tableData);
            }
            document.add(dataTable);
            document.add(PdfFontUtil.getParagraph("\n· 报表描述\n\n", BLOCK_FONT, -1));
            document.add(PdfFontUtil.getParagraph("数据报告可以监控每天的推广情况，" +
                    "可以针对不同的数据表现进行分析，以提升推广效果。", CONTENT_FONT, -1));
            document.newPage();
            document.close();
            writer.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static void createExaminationPdf(ExamPaperSimpleMessage examPaperSimpleMessage, HttpServletResponse response) {
        try {
            // 创建文档
            Document document = new Document();
            response.setContentType("application/pdf");
            String filename = "exam_paper";
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".pdf");
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            // 试卷标题
            document.add(PdfFontUtil.getParagraph(examPaperSimpleMessage.getName(), TITLE_FONT, 1));
            String startTimeStr = "\n考试开始时间：" + examPaperSimpleMessage.getStartTime();
            document.add(PdfFontUtil.getParagraph(startTimeStr, INFO_FONT, -1));
            String endTimeStr = "\t考试结束时间：" + examPaperSimpleMessage.getEndTime();
            document.add(PdfFontUtil.getParagraph(endTimeStr, INFO_FONT, -1));
            // 报告内容
            // 段落标题 + 报表图
            int index = 0;
            Map<String, List<ExaminationIssueList>> listMap = examPaperSimpleMessage.getListMap();
            for (String key : listMap.keySet()) {
                List<ExaminationIssueList> issueLists = listMap.get(key);
                int totalScore = 0;
                for (ExaminationIssueList issueList : issueLists) {
                    totalScore += issueList.getScore();
                }
                document.add(PdfFontUtil.getParagraph("\n\n"+TITLE_INDEX[index] + key + "题（共" + issueLists.size() + "题，共" + totalScore + "分）", NODE_FONT, -1));
                for (int i = 0; i < issueLists.size(); i++) {
                    ExaminationIssueList issueList = issueLists.get(i);
                    IssueBriefMessage issueBriefMessage = issueList.getIssueBriefMessage();
                    if (issueBriefMessage.getType() != 4) {
                        //小题的题目
                        if (!isContainParentheses(issueBriefMessage.getQuestion())) {
                            document.add(PdfFontUtil.getTitleParagraph("\n" + (i + 1) + "." + issueBriefMessage.getQuestion() + "()(本题" + issueList.getScore() + "分)", CONTENT_FONT, -1));
                        }else {
                            document.add(PdfFontUtil.getTitleParagraph("\n" + (i + 1) + "." + issueBriefMessage.getQuestion() + "(本题" + issueList.getScore() + "分)", CONTENT_FONT, -1));
                        }
                        // 图片
                        if (issueBriefMessage.getUrlList().size() != 0) {
                            for (String imagePath : issueBriefMessage.getUrlList()) {
                                if (imagePath.endsWith(".png") || imagePath.endsWith(".jpg") || imagePath.endsWith(".jpeg") || imagePath.endsWith(".webp")) {
                                    float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - 200;
                                    float documentHeight = documentWidth / 580 * 280;
                                    document.add(PdfFontUtil.getImage(imagePath, documentWidth, documentHeight));
                                }
                            }
                        }
                        if (issueBriefMessage.getType() == 2 || issueBriefMessage.getType() == 3) {
                            document.add(PdfFontUtil.getSelectionParagraph("\nA." + issueBriefMessage.getSelectionA(), CONTENT_FONT, -1));
                            document.add(PdfFontUtil.getSelectionParagraph("\nB." + issueBriefMessage.getSelectionB(), CONTENT_FONT, -1));
                            document.add(PdfFontUtil.getSelectionParagraph("\nC." + issueBriefMessage.getSelectionC(), CONTENT_FONT, -1));
                            document.add(PdfFontUtil.getSelectionParagraph("\nD." + issueBriefMessage.getSelectionD(), CONTENT_FONT, -1));
                        }
                    }else {
                        document.add(PdfFontUtil.getTitleParagraph("\n" + (i + 1) + "." + issueBriefMessage.getQuestion() + "(本题" + issueList.getScore() + "分)", CONTENT_FONT, -1));
                        // 图片
                        if (issueBriefMessage.getUrlList().size() != 0) {
                            for (String imagePath : issueBriefMessage.getUrlList()) {
                                if (imagePath.endsWith(".png") || imagePath.endsWith(".jpg") || imagePath.endsWith(".jpeg") || imagePath.endsWith(".webp")) {
                                    float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
                                    float documentHeight = documentWidth / 580 * 320;
                                    document.add(PdfFontUtil.getImage(imagePath, documentWidth, documentHeight));
                                }
                            }
                        }
                        document.add(PdfFontUtil.getParagraph("\n\n\n\n\n\n\n", CONTENT_FONT, -1));
                    }
                }
                index++;
            }
            document.newPage();
            document.close();
            writer.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static boolean isContainParentheses(String str){
        String regex = "\\(.*?\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    private static List<List<String>> getTableData() {
        List<List<String>> tableDataList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            List<String> tableData = new ArrayList<>();
            tableData.add("浙江" + i);
            tableData.add("杭州" + i);
            tableData.add("276" + i);
            tableData.add("33.3%");
            tableData.add("33.3%");
            tableData.add("33.3%");
            tableData.add("33.3%");
            tableData.add("33.3%");
            tableDataList.add(tableData);
        }
        System.out.println(tableDataList);
        return tableDataList;
    }

    private static List<String> tableHead() {
        List<String> tableHeadList = new ArrayList<>();
        tableHeadList.add("省份");
        tableHeadList.add("城市");
        tableHeadList.add("数量");
        tableHeadList.add("百分比");
        tableHeadList.add("百分比");
        tableHeadList.add("百分比");
        tableHeadList.add("百分比2");
        tableHeadList.add("百分比1");
        System.out.println(tableHeadList);
        return tableHeadList;
    }

}

